/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.appintro.utile;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.render.Arc;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.app.Context;

import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 资源工具类
 */
public class ResUtil {
    private static final String TAG = "ResUtil";

    private ResUtil() {
    }

    /**
     * vp转px
     *
     * @param context 上下文
     * @param vp      vp
     * @return px
     */
    public static int vpToPx(Context context, float vp) {
        return (int) (context.getResourceManager().getDeviceCapability().screenDensity / 160 * vp);
    }

    /**
     * px转vp
     *
     * @param context 上下文
     * @param px      px
     * @return vp
     */
    public static int pxTovp(Context context, float px) {
        return (int) (px / (context.getResourceManager().getDeviceCapability().screenDensity / 160));
    }

    /**
     * 获取屏幕的宽
     *
     * @param context 上下文
     * @return 屏幕的宽，单位px
     */
    public static int getScreenWidth(Context context) {
        return vpToPx(context, context.getResourceManager().getDeviceCapability().width);
    }

    /**
     * 获取屏幕的高
     *
     * @param context 上下文
     * @return 屏幕的高，单位px
     */
    public static int getScreenHeight(Context context) {
        return vpToPx(context, context.getResourceManager().getDeviceCapability().height);
    }

    /**
     * 通过资源id获取路径
     *
     * @param context 上下文
     * @param id      资源id
     * @return 资源路径
     */
    public static String getPathById(Context context, int id) {
        String path = "";
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getPathById -> get null context");
            return path;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getPathById -> get null ResourceManager");
            return path;
        }
        try {
            path = manager.getMediaPath(id);
        } catch (IOException | NotExistException | WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getPathById: " + e.getMessage());
        }
        return path;
    }

    /**
     * 通过资源id获取颜色
     *
     * @param context 上下文
     * @param id      资源Id
     * @return 颜色
     */
    public static Color getNewColor(Context context, int id) {
        return new Color(getColor(context, id));
    }

    /**
     * 通过资源id获取颜色
     *
     * @param context 上下文
     * @param id      资源Id
     * @return 颜色
     */
    public static int getColor(Context context, int id) {
        int result = 0;
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getColor -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getColor -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getColor();
        } catch (IOException | WrongTypeException | NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getColor: " + e.getMessage());
        }
        return result;
    }

    /**
     * 通过资源id获取尺寸
     *
     * @param context 上下文
     * @param id      资源Id
     * @return 尺寸
     */
    public static float getDimen(Context context, int id) {
        float result = 0;
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getDimen -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getDimen -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getFloat();
        } catch (IOException | WrongTypeException | NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getDimen: " + e.getMessage());
        }
        return result;
    }

    /**
     * get the boolean value
     *
     * @param context the context
     * @param id      the id
     * @return get the boolean dimen value
     */
    public static boolean getBoolean(Context context, int id) {
        boolean result = false;
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getBoolean -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getBoolean -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getBoolean();
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getBoolean -> IOException");
        } catch (NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getBoolean -> NotExistException");
        } catch (WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getBoolean -> WrongTypeException");
        }
        return result;
    }

    /**
     * get string
     *
     * @param context the context
     * @param id      the string id
     * @return string of the given id
     */
    public static String getString(Context context, int id) {
        String result = "";
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getString -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getString -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getString();
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getString -> IOException");
        } catch (NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getString -> NotExistException");
        } catch (WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getString -> WrongTypeException");
        }
        return result;
    }

    /**
     * get the string array
     *
     * @param context the context
     * @param id      the string array id
     * @return the string array
     */
    public static String[] getStringArray(Context context, int id) {
        String[] result = null;
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getStringArray -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getStringArray -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getStringArray();
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getStringArray -> IOException");
        } catch (NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getStringArray -> NotExistException");
        } catch (WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getStringArray -> WrongTypeException");
        }
        return result;
    }

    /**
     * get the int
     *
     * @param context the context
     * @param id      the int array
     * @return the int array
     */
    public static int getInt(Context context, int id) {
        int result = 0;
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getInt -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getInt -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getInteger();
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getInt -> IOException");
        } catch (NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getInt -> NotExistException");
        } catch (WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getInt -> WrongTypeException");
        }
        return result;
    }

    /**
     * get the int array
     *
     * @param context the context
     * @param id      the int array
     * @return the int array
     */
    public static int[] getIntArray(Context context, int id) {
        int[] result = null;
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getIntArray -> get null context");
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getIntArray -> get null ResourceManager");
            return result;
        }
        try {
            result = manager.getElement(id).getIntArray();
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getIntArray -> IOException");
        } catch (NotExistException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getIntArray -> NotExistException");
        } catch (WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getIntArray -> WrongTypeException");
        }
        return result;
    }

    /**
     * get the vector drawable
     *
     * @param context the context
     * @param id      the drawable id
     * @return the vector drawable
     */
    public static VectorElement getVectorDrawable(Context context, int id) {
        if (null == context) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getVectorDrawable -> get null context");
            return null;
        }
        return new VectorElement(context, id);
    }

    /**
     * get the pixel map
     *
     * @param context the context
     * @param id      the id
     * @return the pixel map
     */
    public static Optional<PixelMap> getPixelMap(Context context, int id) {
        String path = getPathById(context, id);
        if (path.isEmpty()) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getPixelMap -> get empty path");
            return Optional.empty();
        }
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        try {
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "getPixelMap -> IOException");
        }
        return Optional.empty();
    }

    /**
     * get the Pixel Map Element
     *
     * @param context the context
     * @param resId   the res id
     * @return the Pixel Map Element
     */
    public static PixelMapElement getPixelMapDrawable(Context context, int resId) {
        Optional<PixelMap> optional = getPixelMap(context, resId);
        return optional.map(PixelMapElement::new).orElse(null);
    }

    /**
     * get the Element
     *
     * @param color the color
     * @return the Element
     */
    public static Element buildDrawableByColor(int color) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(RgbColor.fromArgbInt(color));
        return drawable;
    }

    /**
     * get the Element By ColorRadius
     *
     * @param color  the color
     * @param radius the radius
     * @return the Element By ColorRadius
     */
    public static Element buildDrawableByColorRadius(int color, float radius) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(RgbColor.fromArgbInt(color));
        drawable.setCornerRadius(radius);
        return drawable;
    }

    /**
     * get the ShapeElement
     *
     * @param thickness  the thickness
     * @param inside     the inside color
     * @param border     the border color
     * @param startAngle the start angle
     * @param sweepAngle the sweep angle
     * @return the ShapeElement
     */
    public static ShapeElement getCustomArcGradientDrawable(int thickness, Color inside, Color border, float startAngle,
                                                            float sweepAngle) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.ARC);
        drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part
        drawable.setArc(new Arc(startAngle, sweepAngle, false));
        drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue()));
        return drawable;
    }

    /**
     * get the Element
     *
     * @param thickness the thickness
     * @param inside    the inside color
     * @param border    the border color
     * @param rect      the rect
     * @return the Element
     */
    public static Element getCustomCircleGradientDrawable(int thickness, Color inside, Color border, Rect rect) {
        ShapeElement element = new ShapeElement();
        element.setShape(ShapeElement.OVAL);
        element.setRgbColor(RgbColor.fromArgbInt(inside.getValue()));
        element.setStroke(thickness, RgbColor.fromArgbInt(border.getValue()));
        element.setBounds(rect);
        return element;
    }

    /**
     * get the Element
     *
     * @param inside the inside color
     * @param rect   the rect
     * @return the Element
     */
    public static Element getCustomRectGradientDrawable(Color inside, Rect rect) {
        ShapeElement element = new ShapeElement();
        element.setShape(ShapeElement.RECTANGLE);
        element.setRgbColor(RgbColor.fromArgbInt(inside.getValue()));
        element.setBounds(rect);
        return element;
    }

    /**
     * 根据Resource获取背景（图片）
     *
     * @param resource 资源
     * @return 位图背景
     * @throws IOException
     * @throws NotExistException
     */
    public static PixelMapElement prepareElement(Resource resource) throws IOException, NotExistException {
        return new PixelMapElement(preparePixelmap(resource));
    }

    /**
     * 根据Resource获取位图
     *
     * @param resource 资源
     * @return 位图
     * @throws IOException
     * @throws NotExistException
     */
    public static PixelMap preparePixelmap(Resource resource) throws IOException, NotExistException {
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        ImageSource imageSource = null;
        try {
            imageSource = ImageSource.create(readResource(resource), srcOpts);
        } finally {
            close(resource);
        }
        if (imageSource == null) {
            throw new FileNotFoundException();
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0);
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;

        PixelMap pixelmap = imageSource.createPixelmap(decodingOpts);
        return pixelmap;
    }

    private static void close(Resource resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                Logger.getLogger(TAG).log(Level.SEVERE, e.getMessage());
            }
        }
    }

    private static byte[] readResource(Resource resource) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bArr = new byte[1024];
        while (true) {
            try {
                int read = resource.read(bArr, 0, 1024);
                if (read == -1) {
                    break;
                }
                byteArrayOutputStream.write(bArr, 0, read);
            } catch (IOException e) {
                HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "readResource failed " + e.getLocalizedMessage());
            } finally {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "readResource failed " + e.getLocalizedMessage());
                }
            }
        }
        HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "readResource finish");
        HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtil().getClass().getName()), "readResource len: " + byteArrayOutputStream.size());
        return byteArrayOutputStream.toByteArray();
    }

}
